package com.yuanqi.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.common.Result;
import com.yuanqi.pojo.CommodityCategory;
import com.yuanqi.service.CommodityCategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品类目接口
 */
@RestController
@RequestMapping("/api/category")
@RequiredArgsConstructor
@Slf4j
public class CommodityCategoryController {
    private final CommodityCategoryService categoryService; // 注入服务

    @PostMapping
    public Result<Boolean> create(@RequestBody CommodityCategory category) {
        return Result.success(categoryService.save(category)); // 新增
    }

    @PutMapping
    public Result<Boolean> update(@RequestBody CommodityCategory category) {
        return Result.success(categoryService.updateById(category));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id,
                                 @RequestParam(defaultValue = "true") Boolean cascade) {
        try {
            if (cascade) {
                // 级联删除：删除分类及其下的所有商品
                log.info("执行级联删除，分类ID: {}", id);
                return Result.success(categoryService.deleteCategoryWithProducts(id));
            } else {
                // 检查是否有商品，如果有则不允许删除
                long productCount = categoryService.countProductsByCategory(id);
                if (productCount > 0) {
                    return Result.error("该分类下有 " + productCount + " 个商品，无法删除。请先删除商品或使用级联删除。");
                }
                return Result.success(categoryService.removeById(id));
            }
        } catch (DataIntegrityViolationException e) {
            log.error("删除分类时发生外键约束错误，分类ID: {}, 错误: {}", id, e.getMessage());
            return Result.error("删除失败：该分类下有商品，无法直接删除。请使用级联删除或先删除相关商品。");
        } catch (Exception e) {
            log.error("删除分类时发生未知错误，分类ID: {}, 错误: {}", id, e.getMessage(), e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }



    /**
     * 检查分类下是否有商品
     */
    @GetMapping("/{id}/products/count")
    public Result<Long> getProductCount(@PathVariable Long id) {
        try {
            return Result.success(categoryService.countProductsByCategory(id));
        } catch (Exception e) {
            log.error("检查分类商品数量失败，分类ID: {}, 错误: {}", id, e.getMessage(), e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }

    /**
     * 检查分类及其子分类下是否有商品
     */
    @GetMapping("/{id}/products/count-recursive")
    public Result<Long> getProductCountRecursively(@PathVariable Long id) {
        try {
            return Result.success(categoryService.countProductsByCategoryRecursively(id));
        } catch (Exception e) {
            log.error("递归检查分类商品数量失败，分类ID: {}, 错误: {}", id, e.getMessage(), e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }

    @GetMapping("/page")
    public Result<Page<CommodityCategory>> page(
            @RequestParam(required = false) String categoryName,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        QueryWrapper<CommodityCategory> qw = new QueryWrapper<>();
        if (StringUtils.isNotBlank(categoryName)) {
            qw.like("category_name", categoryName);
        }
        qw.orderByDesc("created_at");
        return Result.success(categoryService.page(new Page<>(pageNo, pageSize), qw));
    }

    /**
     * 获取所有分类列表（用于下拉菜单）
     */
    @GetMapping("/list")
    public Result<List<CommodityCategory>> list() {
        QueryWrapper<CommodityCategory> qw = new QueryWrapper<>();
        qw.eq("status", 1); // 只获取启用状态的分类
        // 表中无 sort_order 字段，按层级和创建时间排序
        qw.orderByAsc("level").orderByAsc("created_at");
        return Result.success(categoryService.list(qw));
    }

    @GetMapping("/tree")
    public List<CommodityCategory> getTree() {
        return categoryService.listTree();
    }

}


